package com.taotao.netty.socket.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Description: 心跳处理Handler
 * @Author: TaoJF
 * @Date: Created in 2018/6/30 上午10:47
 */
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            String eventType;
            switch (idleStateEvent.state()) {
                case ALL_IDLE:
                    eventType = "读和写空闲";
                    break;
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                default:
                    eventType = "未知";
            }
            System.out.println(ctx.channel().remoteAddress() + "超时事件：" + eventType);
            //事件超时则关闭连接；
            ctx.channel().close();
            System.out.println("服务器端中断和" + ctx.channel().remoteAddress() + "的连接！");
        }
    }
}
